//
//  OBViewModel.swift
//  RXmvvmDemo
//
//  Created by jemi on 2019/12/30.
//  Copyright © 2019 jemi. All rights reserved.
//

import RxSwift
import RxCocoa

class OBViewModel{
    
    //表格数据序列
    let tableData = BehaviorRelay<[String]>(value: [])
    
    //停止头部刷新状态
    let endHeadRefreshing: Observable<Bool>
    
    //停止底部刷新状态
    let endFootRefreshing: Observable<Bool>
    
    //OBViewModel的初始化（根据输入实现对应的输出）
    init(input: (
        headerRefresh: Observable<Void>,
        footerRefresh: Observable<Void> ),
        dependency: (
            disposeBag: DisposeBag,
            networkService: NetWorkService
        )) {
        
        //下拉结果序列
        let headerRefreshData = input.headerRefresh.startWith(()).flatMapLatest {
            _ in
            dependency.networkService.getRandomObserver()   //.takeUntil(input.footerRefresh)
        }.share(replay: 1)
        
        //上拖结果序列
        let footerRefreshData = input.footerRefresh.flatMapLatest{
            _ in
            dependency.networkService.getRandomObserver()
//                .takeUntil(input.headerRefresh)
        }.share(replay: 1)
    
        //生成停止头部刷新状态
        self.endHeadRefreshing = headerRefreshData.map{_ in true}
//            Observable.merge(
//            headerRefreshData.map{_ in true},
//            input.footerRefresh.map{_ in true}
//        )
        
        //生成停止尾部刷新状态
        self.endFootRefreshing = footerRefreshData.map{_ in true}
//            Observable.merge(
//            footerRefreshData.map{_ in true},
//            input.headerRefresh.map{_ in true}
//        )
        
        //下拉刷新时，直接将查询结果替换原数据
        headerRefreshData.subscribe(onNext: { items in
            self.tableData.accept(items)
        }).disposed(by: dependency.disposeBag)
        
        //上拖加载更多时，将查询结果拼接到原数据底部
        footerRefreshData.subscribe(onNext: { items in
            self.tableData.accept(self.tableData.value + items)
        }).disposed(by: dependency.disposeBag)
        
    }
    
    deinit {
        print("销毁了")
    }
}



